package com.itelite.security;

import com.itelite.domain.pojo.User;
import com.itelite.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 **/
@Service
@Slf4j
public class MyUserDetailService implements UserDetailsService {
    //注入登陆的service
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails user = buildUser(username);
        if(user==null) throw new UsernameNotFoundException("用户不存在");
        return user;
    }

    /**
     * 模拟获取登录用户
     * @return 返回用户实例
     */
    private UserDetails buildUser(String userid){
        User user = null;
        user = userMapper.queryUserByUsername(userid);
        if(user!=null){
            user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
        }
        return user;
    }

}
